package com.zlq.cn.service.un;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.api.ApiCodeEnum;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.config.Config;
import com.zlq.cn.dto.BindUserDTO;
import com.zlq.cn.entity.BindUser;
import com.zlq.cn.entity.User;
import com.zlq.cn.entity.UserMsg;
import com.zlq.cn.enums.UserMsgEnum;
import com.zlq.cn.mapper.un.BindUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 绑定用户 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2020-08-26
 */
@Service
public class BindUserService extends ServiceImpl<BindUserMapper, BindUser> {
    @Resource
    private UserService userService;
    @Resource
    private PushService pushService;
    @Resource
    UserMsgService userMsgService;

    public List<BindUserDTO> listByFromUserId(Integer fromUserId, Integer page, Integer pageSize) {
        Page<BindUserDTO> page1 = new Page<>();
        page1.setCurrent(page != null ? page : 1);
        page1.setSize(pageSize != null ? pageSize : Config.BIND_USER_PAGE_SIZE);
        return baseMapper.listByFromUserId(page1, fromUserId).getRecords();
    }

    public void saveBindUser(User loginUser, String phone, String labelName) {
        User user = userService.updateLogin(phone, null, "", true);
        if (user.isNewCreate()) {
            // TODO: 2020/11/1 库里不存在用户增加短信发送或者提示客户端需要邀请
            ResponseException.resultError(ApiCodeEnum.NEED_INVITATION);
        }
        if (getOne(new QueryWrapper<BindUser>()
                        .eq("from_user_id", loginUser.getId())
                        .eq("to_user_id", user.getId())
                , false) != null)
            ResponseException.resultApiError("您已绑定该用户");
        BindUser bindUser = new BindUser();
        bindUser.setFromUserId(loginUser.getId());
        bindUser.setToUserId(user.getId());
        bindUser.setLabelName(labelName);
        bindUser.setCreateTime(LocalDateTime.now());
        bindUser.setUpdateTime(LocalDateTime.now());
        save(bindUser);
        UserMsg userMsg = new UserMsg();
        userMsg.setMsgType(UserMsgEnum.FRIEND_REMINDER_BIND.getType());
        userMsg.setFromUserId(0);
        userMsg.setToUserId(user.getId());
        userMsg.setContent(loginUser.getName() + UserMsgEnum.FRIEND_REMINDER_BIND.getMsgContent());
        userMsg.setCreateTime(LocalDateTime.now());
        userMsg.setUpdateTime(LocalDateTime.now());
        userMsgService.save(userMsg);
        loginUser.setFriendNum(loginUser.getFriendNum() != null ? loginUser.getFriendNum() + 1 : 1);
        userService.setUserByIdCache(loginUser);
        pushService.pushAccount(user.getProject(), Collections.singletonList(user.getId()),
                UserMsgEnum.FRIEND_REMINDER_BIND.getMsgTitle(),
                loginUser.getName() + UserMsgEnum.FRIEND_REMINDER_BIND.getMsgContent(), null);
        userService.update(new UpdateWrapper<User>().setSql(true, "friend_num = friend_num+1").eq("id", loginUser.getId()));
        User one = userService.getOne(new QueryWrapper<User>()
                        .eq("id", user.getId())
                , false);
        if (one != null) {
            if (getOne(new QueryWrapper<BindUser>()
                            .eq("from_user_id", user.getId())
                            .eq("to_user_id", loginUser.getId())
                    , false) == null) {
                bindUser = new BindUser();
                bindUser.setFromUserId(user.getId());
                bindUser.setToUserId(loginUser.getId());
                bindUser.setLabelName(labelName);
                bindUser.setCreateTime(LocalDateTime.now());
                bindUser.setUpdateTime(LocalDateTime.now());
                save(bindUser);
                User userByIdCache = userService.getUserByIdCache(one.getId());
                if (userByIdCache != null) {
                    userByIdCache.setFriendNum(userByIdCache.getFriendNum() != null ? userByIdCache.getFriendNum() + 1 : 1);
                    userService.setUserByIdCache(userByIdCache);
                }
                userService.update(new UpdateWrapper<User>().setSql(true, "friend_num = friend_num+1").eq("id", one.getId()));
            }
        }
    }

    public void saveUnBindUser(User loginUser, Integer bindId) {
        if (remove(new LambdaUpdateWrapper<BindUser>()
                .eq(BindUser::getFromUserId, loginUser.getId())
                .eq(BindUser::getId, bindId))) {
            loginUser.setFriendNum(loginUser.getFriendNum() != null ? loginUser.getFriendNum() - 1 : 0);
            userService.setUserByIdCache(loginUser);
            userService.update(new UpdateWrapper<User>().setSql(true, "friend_num = IF(friend_num <= 0, 0, friend_num - 1)").eq("id", loginUser.getId()));
        }
    }
}
